package com.dieusoft.box.ship.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dieusoft.box.info.entity.JzxInfo;
import com.dieusoft.box.info.service.IJzxInfoService;
import com.dieusoft.box.ship.entity.BillOfLadingInfo;
import com.dieusoft.box.ship.entity.ContainerCargoInfo;
import com.dieusoft.box.ship.entity.DeclareAtCustomsInfo;
import com.dieusoft.box.ship.entity.ShipExport;
import com.dieusoft.box.ship.service.BillOfLadingInfoService;
import com.dieusoft.box.ship.service.ContainerCargoInfoService;
import com.dieusoft.box.ship.service.DeclareAtCustomsInfoService;
import com.dieusoft.box.ship.service.ShipExportService;
import com.dieusoft.box.ship.vo.BillOfLadingInfoVO;
import com.dieusoft.box.ship.vo.ContainerCargoInfoVO;
import com.dieusoft.box.ship.vo.CostInfoVO;
import com.dieusoft.box.ship.vo.DeclareAtCustomsVO;
import com.dieusoft.box.trade.entity.CostInfo;
import com.dieusoft.box.trade.service.ICostInfoService;
import com.google.common.base.Joiner;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 海运管理
 * @Date: 2020-10-16
 * @Version: V1.0
 */
@Api(tags = "海运管理")
@RestController
@RequestMapping("/box.ship/shipInfo")
@Slf4j
public class ShipController {

    @Autowired
    private ShipExportService shipExportService;

    @Autowired
    private BillOfLadingInfoService billOfLadingInfoService;

    @Autowired
    private DeclareAtCustomsInfoService declareAtCustomsInfoService;

    @Autowired
    private ContainerCargoInfoService containerCargoInfoService;

    @Autowired
    private ICostInfoService costInfoService;

    @Autowired
    private IJzxInfoService jzxInfoService;

//    @Autowired
//    private IBillInfoService billInfoService;

    /**
     * 分页列表查询
     *
     * @param shipExport
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @PermissionData(pageComponent = "seaexport/ShipExportList")
    @AutoLog(value = "海运管理-分页列表查询")
    @ApiOperation(value = "海运管理-分页列表查询", notes = "海运管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(ShipExport shipExport,
                                   @RequestParam(name = "so", defaultValue = "0") Integer so,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<ShipExport> queryWrapper = QueryGenerator.initQueryWrapper(shipExport, req.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (sysUser.getUsername().equals("admin")) {
            queryWrapper.like("sys_org_code", "%");
        }
        //只查询自己的
        if (so == 1) {
            queryWrapper.eq("create_by", sysUser.getUsername());
        }

        //TODO 列表统计需要优化
        List<ShipExport> list = shipExportService.list(queryWrapper);
        Map<String, Integer> boxDetailMap = new HashMap<>();
        Integer TEUCount = 0;
        for (ShipExport se : list) {
            if (StringUtils.isNotBlank(se.getBoxInfo())) {
                JSONObject boxInfo = JSONObject.parseObject(se.getBoxInfo());
                JSONArray boxList = boxInfo.getJSONArray("boxList");
                if (boxList.size() > 0) {
                    for (Object box : boxList) {
                        JSONObject boxJson = JSONObject.parseObject(box.toString());
                        Integer boxl = boxJson.getInteger("boxl");
                        String boxtype = boxJson.getString("boxtype");
                        Integer boxTypeCount = boxDetailMap.get(boxtype);
                        //计算箱型信息
                        boxDetailMap.put(boxtype, null == boxTypeCount ? boxl : boxTypeCount + boxl);
                        //计算TEU
                        Integer boxTypeNum = null;
                        try {
                            boxTypeNum = Integer.parseInt(boxtype.substring(0, 2));
                            if (boxTypeNum == 20) {
                                TEUCount += 1;
                            } else if (boxTypeNum == 40 || boxTypeNum == 45) {
                                TEUCount += 2;
                            } else if (boxTypeNum == 53) {
                                TEUCount += 3;
                            }
                        } catch (NumberFormatException e) {
                            log.error("箱型前两位不是数字");
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        Page<ShipExport> page = new Page<ShipExport>(pageNo, pageSize);
        IPage<ShipExport> pageList = shipExportService.page(page, queryWrapper);
        StringBuffer sb = new StringBuffer();
        sb.append("票数：").append(pageList.getTotal()).append("，箱TEU：").append(TEUCount).append("，");
        for (Map.Entry<String, Integer> en : boxDetailMap.entrySet()) {
            //取出key value 拼接字符串
            sb.append(en.getKey()).append("：").append(en.getValue()).append("，");
        }
        return Result.OK(sb.toString(), pageList);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "海运管理-批量删除")
    @ApiOperation(value = "海运管理-批量删除", notes = "海运管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    @Transactional(rollbackOn = Exception.class)
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        //基本信息
        shipExportService.removeByIds(Arrays.asList(ids.split(",")));
        //报关
        QueryWrapper<ContainerCargoInfo> containerCargoInfoQueryWrapper = new QueryWrapper();
        containerCargoInfoQueryWrapper.in("ship_id", Arrays.asList(ids.split(",")));
        containerCargoInfoService.remove(containerCargoInfoQueryWrapper);
        //提单
        QueryWrapper<BillOfLadingInfo> billOfLadingInfoQueryWrapper = new QueryWrapper();
        billOfLadingInfoQueryWrapper.in("ship_id", Arrays.asList(ids.split(",")));
        billOfLadingInfoService.remove(billOfLadingInfoQueryWrapper);
        //费用
        QueryWrapper<CostInfo> costInfoQueryWrapper = new QueryWrapper();
        costInfoQueryWrapper.in("buis_id", Arrays.asList(ids.split(",")));
        costInfoService.remove(costInfoQueryWrapper);

        return Result.OK("批量删除成功！");
    }

    /**
     * 添加
     *
     * @param shipExport
     * @return
     */
    @AutoLog(value = "海运管理-添加")
    @ApiOperation(value = "海运管理-添加", notes = "海运管理-添加")
    @PostMapping(value = "/add")
    @Transactional(rollbackOn = Exception.class)
    public Result<?> add(@RequestBody ShipExport shipExport) {
        shipExport.setOrderNumber(getOrderNumber());
        try {
            shipExportService.save(shipExport);
        } catch (DuplicateKeyException e) {
            return Result.error(shipExport.getCustomerNumber() + "的客户业务编号已存在，不能重复新增。");
        }
        //保存提单的收发通信息
        if (StringUtils.isNoneBlank(shipExport.getMainOffNumber())) {
            BillOfLadingInfo billOfLadingInfo = new BillOfLadingInfo();
            billOfLadingInfo.setType("MBL");
            JSONArray mainOffNumber = JSON.parseArray(shipExport.getMainOffNumberJp());
            mainOffNumber.add(shipExport.getMainOffNumber());
            billOfLadingInfo.setMainOffNumberData(mainOffNumber.toString());
            billOfLadingInfo.setTitle("提单1");
            billOfLadingInfo.setConsignee(shipExport.getConsignee());
            billOfLadingInfo.setConsignor(shipExport.getConsignor());
            billOfLadingInfo.setNotifier(shipExport.getNotifier());
            billOfLadingInfo.setSecNotifier(shipExport.getSecNotifier());
            billOfLadingInfo.setFormForeignAgent(shipExport.getFormForeignAgent());
            billOfLadingInfo.setShipMarks(shipExport.getShipMarks());
            billOfLadingInfo.setEnName(shipExport.getEnName());
            billOfLadingInfo.setShipId(shipExport.getId());
            billOfLadingInfoService.save(billOfLadingInfo);
        }

        //获取删除的箱子id
        String boxInfo = shipExport.getBoxInfo();
        JSONObject jsonObject = JSONObject.parseObject(boxInfo);
        Object deleteBoxNumIds = jsonObject.get("deleteBoxNumIds");
        String strDeleteBoxNumIds = "";
        if (null != deleteBoxNumIds) {
            strDeleteBoxNumIds = deleteBoxNumIds.toString();
        }
        //更新删除的箱子状态为可用
        if (StringUtils.isNotBlank(strDeleteBoxNumIds)) {
            updateJzxInfo(strDeleteBoxNumIds.substring(0, strDeleteBoxNumIds.length() - 1), 1, null);
        }

        //获取添加的箱子
        JSONArray boxList = jsonObject.getJSONArray("boxList");
        String newBoxNum = "";
        for (int i = 0; i < boxList.size(); i++) {
            JSONObject j = new JSONObject((Map<String, Object>) boxList.get(i));
            newBoxNum = newBoxNum + j.getString("boxnum") + ",";
        }

        //如果有添加的箱子，设置集装箱状态和客户业务编号
        if (StringUtils.isNotBlank(newBoxNum)) {
            updateJzxInfo(newBoxNum.substring(0, newBoxNum.length() - 1), 0, shipExport.getCustomerNumber());
        }
        return Result.OK("添加成功", shipExport.getId());
    }


    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "海运管理-通过id查询")
    @ApiOperation(value = "海运管理-通过id查询", notes = "海运管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        ShipExport shipExport = shipExportService.getById(id);
        if (null == shipExport) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(shipExport);

    }

    /**
     * 导出excel
     *
     * @param request
     * @param shipExport
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ShipExport shipExport) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // Step.1 组装查询条件查询数据
        QueryWrapper<ShipExport> queryWrapper = QueryGenerator.initQueryWrapper(shipExport, request.getParameterMap());
        queryWrapper.eq("sys_org_code", sysUser.getOrgCode());
        //Step.2 获取导出数据
        List<ShipExport> queryList = shipExportService.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<ShipExport> shipExportList = new ArrayList<ShipExport>();
        if (oConvertUtils.isEmpty(selections)) {
            shipExportList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            shipExportList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        String[] cols = request.getParameter("field").split(",");
        List filterCols = new ArrayList();
        for (String str : cols) {
            if (StringUtils.isNoneBlank(str) && !"action".equals(str) && !"id".equals(str) && !"status".equals(str)) {
                filterCols.add(str.replaceAll("_dictText", ""));
            }
        }
        String exportFields = Joiner.on(",").join(filterCols);
        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "海运数据");
        mv.addObject(NormalExcelConstants.CLASS, ShipExport.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("海运数据", "导出人:" + sysUser.getRealname(), "集装箱数据"));
        mv.addObject(NormalExcelConstants.DATA_LIST, shipExportList);
        mv.addObject(NormalExcelConstants.EXPORT_FIELDS, exportFields);
        return mv;
    }

    /**
     * 编辑
     *
     * @param shipExport
     * @return
     */
    @AutoLog(value = "海运管理-编辑")
    @ApiOperation(value = "海运管理-编辑", notes = "海运管理-编辑")
    @PutMapping(value = "/edit")
    @Transactional(rollbackOn = Exception.class)
    public Result<?> edit(@RequestBody ShipExport shipExport) {
        if (StringUtils.isEmpty(shipExport.getId())) {
            return Result.error("ID不能为空");
        }
        ShipExport shipExportEntity = shipExportService.getById(shipExport.getId());
        if (null == shipExportEntity) {
            return Result.error("未找到对应数据");
        }
        shipExport.setOrderNumber(shipExportEntity.getOrderNumber());
        try {
            shipExportService.updateById(shipExport);
        } catch (Exception e) {
            return Result.error(shipExport.getCustomerNumber() + "的客户业务编号已存在，不能重复新增。");
        }
        //更新提单的收发通信息
        List<BillOfLadingInfo> billOfLadingInfo = billOfLadingInfoService.findByShipId(shipExport.getId());
        billOfLadingInfo.stream().forEach(item -> {
            JSONArray otherOffNumber = JSON.parseArray(shipExport.getOtherOffNumberJp());
            otherOffNumber.add(shipExport.getOtherOffNumber());
            item.setOtherOffNumberData(otherOffNumber.toString());
            JSONArray mainOffNumber = JSON.parseArray(shipExport.getMainOffNumberJp());
            mainOffNumber.add(shipExport.getMainOffNumber());
            item.setMainOffNumberData(mainOffNumber.toString());
            billOfLadingInfoService.updateById(item);
        });

        //获取删除的箱子id
        String boxInfo = shipExport.getBoxInfo();
        JSONObject jsonObject = JSONObject.parseObject(boxInfo);
        Object deleteBoxNumIds = jsonObject.get("deleteBoxNumIds");
        String strDeleteBoxNumIds = "";
        if (null != deleteBoxNumIds) {
            strDeleteBoxNumIds = deleteBoxNumIds.toString();
        }
        //更新删除的箱子状态为可用
        if (StringUtils.isNotBlank(strDeleteBoxNumIds)) {
            updateJzxInfo(strDeleteBoxNumIds.substring(0, strDeleteBoxNumIds.length() - 1), 1, null);
        }

        //获取添加的箱子
        JSONArray boxList = jsonObject.getJSONArray("boxList");
        String newBoxNum = "";
        for (int i = 0; i < boxList.size(); i++) {
            JSONObject j = new JSONObject((Map<String, Object>) boxList.get(i));
            newBoxNum = newBoxNum + j.getString("boxnum") + ",";
        }

        //如果有添加的箱子，设置集装箱状态和客户业务编号
        if (StringUtils.isNotBlank(newBoxNum)) {
            updateJzxInfo(newBoxNum.substring(0, newBoxNum.length() - 1), 0, shipExport.getCustomerNumber());
        }
        return Result.OK("编辑成功", shipExport.getId());
    }

    /**
     * 生成账单号
     *
     * @return
     */
    private synchronized String getOrderNumber() {
        final StringBuffer sb = new StringBuffer().append("SE");
        final String yymmdd = DateTimeFormatter.ofPattern("yyMMdd").format(LocalDate.now());
        sb.append(yymmdd);
        String s = sb.toString();
        Integer count = shipExportService.selectCountByPrefix(s + "%");
        String orderNumber = String.format("%0" + 4 + "d", count + 1);
        return sb.append(orderNumber).toString();
    }

    /*********************************************************提单信息管理*********************************************************/
    /**
     * 提单信息保存
     *
     * @param jsonData
     * @return
     */
    @AutoLog(value = "海运管理-提单信息-添加")
    @ApiOperation(value = "海运管理-提单信息-添加", notes = "海运管理-提单信息-添加")
    @PostMapping(value = "/tidan/add")
    @Transactional(rollbackOn = Exception.class)
    public Result<?> addTidan(@RequestBody JSONObject jsonData) {
        BillOfLadingInfoVO billOfLadingInfoVO = JSONObject.parseObject(jsonData.toJSONString(), BillOfLadingInfoVO.class);
        QueryWrapper<BillOfLadingInfo> billOfLadingInfoQueryWrapper = new QueryWrapper<>();
        billOfLadingInfoQueryWrapper.eq("ship_id", jsonData.getString("shipId"));
        billOfLadingInfoService.remove(billOfLadingInfoQueryWrapper);
        billOfLadingInfoVO.getMBL().stream().forEach(item -> {
//            if (StringUtils.isEmpty(item.getId())) {
            item.setId(null);
            item.setShipId(jsonData.getString("shipId"));
            billOfLadingInfoService.save(item);
//            } else {
//                billOfLadingInfoService.updateById(item);
//            }
        });
        billOfLadingInfoVO.getHBL().stream().forEach(item -> {
//            if (StringUtils.isEmpty(item.getId())) {
            item.setId(null);
            item.setShipId(jsonData.getString("shipId"));
            billOfLadingInfoService.save(item);
//            } else {
//                billOfLadingInfoService.updateById(item);
//            }
        });
        return Result.OK("添加成功！");
    }

    /**
     * 提单信息查询
     *
     * @param shipId
     * @return
     */
    @AutoLog(value = "海运管理-提单信息-查询")
    @ApiOperation(value = "海运管理-提单信息-查询", notes = "海运管理-提单信息-查询")
    @GetMapping(value = "/tidan/queryByShipId")
    public Result<?> addTidan(@RequestParam(name = "shipId", required = true) String shipId) {
        List<BillOfLadingInfo> billOfLadingInfo = billOfLadingInfoService.findByShipId(shipId);
        BillOfLadingInfoVO billOfLadingInfoVO = new BillOfLadingInfoVO();
        List<BillOfLadingInfo> MBLData = new ArrayList<>();
        List<BillOfLadingInfo> HBLData = new ArrayList<>();
        billOfLadingInfo.stream().forEach(item -> {
            if (item.getType().equals("MBL")) {
                MBLData.add(item);
                billOfLadingInfoVO.setMainOffNumberData(item.getMainOffNumberData());
            } else if (item.getType().equals("HBL")) {
                HBLData.add(item);
                billOfLadingInfoVO.setOtherOffNumberData(item.getOtherOffNumberData());
            }
        });
        billOfLadingInfoVO.setMBL(MBLData);
        billOfLadingInfoVO.setHBL(HBLData);
        return Result.OK(billOfLadingInfoVO);
    }
    /*********************************************************报关信息管理*********************************************************/

    /**
     * 报关信息保存
     *
     * @param jsonData
     * @return
     */
    @AutoLog(value = "海运管理-报关信息-添加")
    @ApiOperation(value = "海运管理-报关信息-添加", notes = "海运管理-报关信息-添加")
    @PostMapping(value = "/baoguan/add")
    @Transactional(rollbackOn = Exception.class)
    public Result<?> addBaoguan(@RequestBody JSONObject jsonData) {
        List<DeclareAtCustomsInfo> declareAtCustomsInfoList = new ArrayList<>();
        declareAtCustomsInfoList = JSONObject.parseArray(jsonData.getJSONArray("declareAtCustomsInfoList").toJSONString(), DeclareAtCustomsInfo.class);
        final String shipId = jsonData.getString("shipId");
        declareAtCustomsInfoService.deleteAll();

        declareAtCustomsInfoList.stream().forEach(item -> {
            item.setShipId(shipId);
            item.setId(null);
            declareAtCustomsInfoService.save(item);
        });
        return Result.OK("添加成功！");
    }

    /**
     * 报关信息查询
     *
     * @param shipId
     * @return
     */
    @AutoLog(value = "海运管理-报关信息-查询")
    @ApiOperation(value = "海运管理-报关信息-查询", notes = "海运管理-报关信息-查询")
    @GetMapping(value = "/baoguan/queryByShipId")
    public Result<?> queryBaoguan(@RequestParam(name = "shipId", required = true) String shipId) {
        ShipExport shipExport = shipExportService.getById(shipId);
        String mainOffNumberJp = shipExport.getMainOffNumberJp();
        JSONArray mainOffNumberList = JSON.parseArray(mainOffNumberJp);
        mainOffNumberList.add(shipExport.getMainOffNumber());
        List<DeclareAtCustomsInfo> declareAtCustomsInfos = declareAtCustomsInfoService.findByShipId(shipId);
        DeclareAtCustomsVO declareAtCustomsVO = new DeclareAtCustomsVO();
        declareAtCustomsVO.setDeclareAtCustomsInfoList(declareAtCustomsInfos);
        declareAtCustomsVO.setMainOffNumbersData(mainOffNumberList.toJSONString());
        List<ContainerCargoInfo> containerCargoInfos = containerCargoInfoService.findByShipId(shipId);
        Set<String> boxNumbers = new HashSet<>();
        for (int i = 0; i < containerCargoInfos.size(); i++) {
            JSONObject jsonObject = JSONObject.parseObject(containerCargoInfos.get(i).getBoxInfo());
            if (null != jsonObject.getJSONArray("boxList")) {
                JSONArray boxList = jsonObject.getJSONArray("boxList");
                boxList.stream().forEach(item -> {
                    JSONObject object = JSONObject.parseObject(item.toString());
                    boxNumbers.add(object.getString("boxnum"));
                });
                break;
            }
        }
        declareAtCustomsVO.setBoxNumberData(JSONArray.toJSONString(boxNumbers));
        return Result.OK(declareAtCustomsVO);
    }

    /*********************************************************箱货信息管理*********************************************************/

    /**
     * 箱货信息查询
     *
     * @param shipId
     * @return
     */
    @AutoLog(value = "海运管理-箱货信息-查询")
    @ApiOperation(value = "海运管理-箱货信息-查询", notes = "海运管理-箱货信息-查询")
    @GetMapping(value = "/xianghuo/queryByShipId")
    public Result<?> queryXiangHuo(@RequestParam(name = "shipId", required = true) String shipId) {
        ShipExport shipExport = shipExportService.getById(shipId);
        //关单号
        String mainOffNumberJp = shipExport.getMainOffNumberJp();
        JSONArray mainOffNumberList = JSON.parseArray(mainOffNumberJp);
        mainOffNumberList.add(shipExport.getMainOffNumber());
        //分单号
        String otherOffNumberJp = shipExport.getOtherOffNumberJp();
        JSONArray otherOffNumberList = JSON.parseArray(otherOffNumberJp);
        otherOffNumberList.add(shipExport.getOtherOffNumber());

        List<ContainerCargoInfo> containerCargoInfoList = containerCargoInfoService.findByShipId(shipId);
        ContainerCargoInfoVO containerCargoInfoVO = new ContainerCargoInfoVO();
        containerCargoInfoVO.setOtherOffNumbersData(otherOffNumberList.toJSONString());
        containerCargoInfoVO.setMainOffNumbersData(mainOffNumberList.toJSONString());
        containerCargoInfoVO.setContainerCargoInfos(containerCargoInfoList);
        return Result.OK(containerCargoInfoVO);
    }

    /**
     * 箱货信息保存
     *
     * @param jsonData
     * @return
     */
    @AutoLog(value = "海运管理-箱货信息-添加")
    @ApiOperation(value = "海运管理-箱货信息-添加", notes = "海运管理-箱货信息-添加")
    @PostMapping(value = "/xianghuo/add")
    @Transactional(rollbackOn = Exception.class)
    public Result<?> addXiangHuo(@RequestBody JSONObject jsonData) {
        List<ContainerCargoInfo> containerCargoInfoList = new ArrayList<>();
        containerCargoInfoList = JSONObject.parseArray(jsonData.getJSONArray("containerCargoInfos").toJSONString(), ContainerCargoInfo.class);
        final String shipId = jsonData.getString("shipId");
        containerCargoInfoService.deleteAll();
//        //获取删除的箱子id
//        Object deleteBoxNumIds = jsonData.get("deleteBoxNumIds");
//        String strDeleteBoxNumIds = "";
//        if (null != deleteBoxNumIds) {
//            strDeleteBoxNumIds = deleteBoxNumIds.toString();
//        }
//        //更新删除的箱子状态为可用
//        if (StringUtils.isNotBlank(strDeleteBoxNumIds)) {
//            updateJzxInfo(strDeleteBoxNumIds.substring(0, strDeleteBoxNumIds.length() - 1), 1, null);
//        }
//
//        //获取添加的箱子
//        JSONArray boxList = jsonData.getJSONObject("boxInfo").getJSONArray("boxList");
//        String newBoxNum = "";
//        for (int i = 0; i < boxList.size(); i++) {
//            JSONObject j = new JSONObject((Map<String, Object>) boxList.get(i));
//            newBoxNum = newBoxNum + j.getString("boxnum") + ",";
//        }
//
//        //如果有添加的箱子，设置集装箱状态和客户业务编号
//        if (StringUtils.isNotBlank(newBoxNum)) {
//            ShipExport shipExport = shipExportService.getById(shipId);
//            updateJzxInfo(newBoxNum.substring(0, newBoxNum.length() - 1), 0, shipExport.getCustomerNumber());
//        }
//        containerCargoInfoList.get(0).setBoxInfo(jsonData.getJSONObject("boxInfo").toJSONString());
        containerCargoInfoList.stream().forEach(item -> {
            item.setShipId(shipId);
            item.setId(null);
            containerCargoInfoService.save(item);
        });
        return Result.OK("添加成功！");
    }

    /**
     * 修改集装箱状态和客户业务编号
     *
     * @param ids
     * @param status
     * @param customerBusinessNumber
     */
    private void updateJzxInfo(String ids, int status, String customerBusinessNumber) {
        String[] splitIds = ids.split(",");
        for (String id : splitIds) {
            QueryWrapper<JzxInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("container_number", id);
            JzxInfo jzxInfo = jzxInfoService.getOne(queryWrapper);
            if (null != jzxInfo) {
                jzxInfo.setStatus(status);
                jzxInfo.setUpdateTime(new Date());
                if (status == 0) {
                    jzxInfo.setCustomerBusinessNumber(customerBusinessNumber);
                } else {
                    jzxInfo.setCustomerBusinessNumber(null);
                    jzxInfo.setOverdueStorageFee("0");
                    jzxInfo.setOverstockingDays(0);
                    jzxInfo.setInTime(null);
                    jzxInfo.setOutTime(null);
                    jzxInfo.setTotalDepositDays(0);
                }
                jzxInfoService.updateById(jzxInfo);
            }
        }
    }


    /*********************************************************费用信息管理*********************************************************/

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @PostMapping(value = "/cost/del")
    @Transactional(rollbackOn = Exception.class)
    public Result remove(@RequestBody JSONObject ids) {
        List<String> list = new ArrayList<>();
        for (Object o : ids.getJSONArray("ids")) {
            list.add(o.toString());
        }
        boolean b = costInfoService.removeByIds(list);
        return b ? Result.OK().success("删除成功") : Result.error("删除失败");
    }

    @PostMapping(value = "/cost/revoke/submit")
    @Transactional(rollbackOn = Exception.class)
    public Result revokeSubmit(@RequestBody JSONObject data) {
        String businessId = data.getString("businessId");
        if (StringUtils.isBlank(businessId)) {
            return Result.error("撤销提交失败-空数据");
        } else {
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.set("s_code", 1);
            updateWrapper.set("status", "录入状态");
            updateWrapper.eq("buis_id", businessId);
            updateWrapper.eq("s_code", 2);
            boolean costUpdateRt = costInfoService.update(updateWrapper);
            return costUpdateRt ? Result.OK().success("撤销提交成功") : Result.error("撤销提交失败");
        }
    }

    @PostMapping(value = "/cost/check")
    @Transactional(rollbackOn = Exception.class)
    public Result check(@RequestBody JSONObject data) {
        List<Object> ids1 = data.getJSONArray("ids").stream().collect(Collectors.toList());
        Integer type = data.getInteger("type");
        if (ids1.size() == 0 || null == type) {
            return Result.error("费用审核失败");
        } else {
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.set("s_code", type + 2);
            String status = null;
            Integer sCode = 0;
            if (type == 1) {
                status = "审核通过";
                sCode = 3;
            } else if (type == 2) {//驳回状态改为录入状态
                status = "录入状态";
                sCode = 1;
            } else if (type == 3) {//撤销审核状态改为审核中
                status = "审核中";
                sCode = 2;
            }
            updateWrapper.set("status", status);
            updateWrapper.set("s_code", sCode);
            updateWrapper.in("id", ids1);
            boolean costUpdateRt = costInfoService.update(updateWrapper);
            return costUpdateRt ? Result.OK().success("操作成功") : Result.error("操作失败");
        }
    }

    /**
     * 审核费用列表信息查询
     *
     * @param shipId
     * @return
     */
    @GetMapping(value = "/cost/queryCheckList")
    public Result<?> queryCostInfosByCheck(@RequestParam(name = "shipId", required = true) String shipId) {
        QueryWrapper<CostInfo> YsQueryWrapper = new QueryWrapper();
        YsQueryWrapper.eq("type", "ys");
        YsQueryWrapper.eq("buis_id", shipId);
        YsQueryWrapper.ne("s_code", 1);
        List<CostInfo> ysList = costInfoService.list(YsQueryWrapper);
        QueryWrapper<CostInfo> YfQueryWrapper = new QueryWrapper();
        YfQueryWrapper.eq("type", "yf");
        YfQueryWrapper.eq("buis_id", shipId);
        YfQueryWrapper.ne("s_code", 1);
        List<CostInfo> yfList = costInfoService.list(YfQueryWrapper);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("ysList", ysList);
        jsonObject.put("yfList", yfList);
        return Result.OK(jsonObject);
    }

    /**
     * 提交审核
     * 提交审核时需要创建账单
     *
     * @param data
     * @return
     */
    @PostMapping(value = "/cost/submit/check")
    @Transactional(rollbackOn = Exception.class)
    public Result submitCheck(@RequestBody JSONObject data) {
        List<Object> ids1 = data.getJSONArray("ids").stream().collect(Collectors.toList());
        if (ids1.size() == 0) {
            return Result.error("提交审核失败-空数据");
        }

        //更改状态为审核中
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.set("s_code", 2);
        updateWrapper.set("status", "审核中");
        updateWrapper.in("id", ids1);
        boolean b = costInfoService.update(updateWrapper);

//        //根据业务ID查询出审核中的费用信息，用来计算账单金额
//        QueryWrapper<CostInfo> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("s_code", 2);
//        queryWrapper.eq("buis_id", modelId);
//        List<CostInfo> costInfoList = costInfoService.list(queryWrapper);
//
//        //账单总金额
//        BigDecimal totalAmount = BigDecimal.ZERO;
//        //账单币种
//        String currency = null;
//
//        String billNumber = getBillNumber();
//        for (int i = 0; i < costInfoList.size(); i++) {
//            totalAmount = totalAmount.add(costInfoList.get(i).getTotalPrice());
//            //TODO 这里只取第一个费用的币种，如果费用明细中币种不一致。此处需要调整
//            if (null == currency) {
//                currency = costInfoList.get(i).getCurrency();
//            }
//        }
//
//        //判断账单是否存在
//        QueryWrapper<BillInfo> billInfoQueryWrapper = new QueryWrapper<>();
//        billInfoQueryWrapper.eq("business_id", modelId);
//        BillInfo one = billInfoService.getOne(billInfoQueryWrapper);
//        if (null == one) {
//            /**
//             * 生成账单
//             */
//            BillInfo billInfo = new BillInfo();
//            //账单类型
//            billInfo.setBillNumber(billNumber);
//            //结算单位
//            billInfo.setSettlementCompany(data.getString("settlementCompany"));
//            //账单类型
//            billInfo.setBuisType(data.getString("billType"));
//            //待审核
//            billInfo.setStatus("1");
//            //账单金额和币种
//            billInfo.setCurrency(currency);
//            billInfo.setAmount(totalAmount.toString());
//            billInfo.setBusinessId(modelId);
//            boolean b1 = billInfoService.save(billInfo);
//            if (!b1) {
//                return Result.error("提交审核失败");
//            }
//        } else {
//            //更新账单费用
//            billNumber = one.getBillNumber();
//            one.setAmount(totalAmount.toString());
//        }
//        //根据业务ID更新已提交审核费用的账单号
//        for (int i = 0; i < costInfoList.size(); i++) {
//            costInfoList.get(i).setBillNumber(billNumber);
//        }
//        boolean b = costInfoService.updateBatchById(costInfoList);

        return b ? Result.OK().success("已提交审核") : Result.error("提交审核失败");
    }

    /**
     * 费用信息保存
     *
     * @param costInfoVO
     * @return
     */
    @AutoLog(value = "海运管理-费用信息-添加")
    @ApiOperation(value = "海运管理-费用信息-添加", notes = "海运管理-费用信息-添加")
    @PostMapping(value = "/cost/add")
    @Transactional(rollbackOn = Exception.class)
    public Result<?> addCostInfo(@RequestBody CostInfoVO costInfoVO) {

        if (StringUtils.isAnyBlank(costInfoVO.getShipId(), costInfoVO.getType())) {
            return Result.error("费用保存失败");
        }
//        List<CostInfo> costInfos = costInfoService.selectByMainId(costInfoVO.getShipId(), costInfoVO.getType());
//        List<String> ids = costInfos.stream().map(item -> item.getId()).collect(Collectors.toList());
//        List<String> tempIds = new ArrayList<>();
//        costInfoVO.getCostInfoList().stream().forEach(item -> {
//            if (item.getId().indexOf("row_") == -1) {
//                tempIds.add(item.getId());
//            }
//        });
//        ids.removeAll(tempIds);
//        if (ids.size() > 0) {
//            costInfoService.deleteByMainIdAndType(ids);
//        }

        costInfoVO.getCostInfoList().stream().forEach(item -> {
            if (item.getId().indexOf("row_") == 0) {
                item.setBuisId(costInfoVO.getShipId());
                item.setId(null);
                if (costInfoVO.getType().equals("ys")) {
                    item.setType("ys");
                    item.setBillType("应收");
                } else if (costInfoVO.getType().equals("yf")) {
                    item.setType("yf");
                    item.setBillType("应付");
                }
                costInfoService.save(item);
            } else {
                costInfoService.updateById(item);
            }
        });
        return Result.OK("保存成功！");
    }

    /**
     * 费用信息查询
     *
     * @param shipId
     * @return
     */
    @GetMapping(value = "/cost/queryByShipId")
    public Result<?> queryCostInfos(@RequestParam(name = "shipId", required = true) String shipId) {
        List<CostInfo> ysList = costInfoService.selectByMainId(shipId, "ys");
        List<CostInfo> yfList = costInfoService.selectByMainId(shipId, "yf");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("ysList", ysList);
        jsonObject.put("yfList", yfList);
        return Result.OK(jsonObject);
    }
}
